package com.ruoyi.different.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.different.domain.DifferentRete;
import com.ruoyi.different.domain.WxAddBody;
import com.ruoyi.different.service.IDifferentReteService;
import com.ruoyi.different.service.impl.WeixinFsfunction;
import com.ruoyi.different.service.impl.WeixinGetOpenId;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 异网数据Controller
 * 
 * @author rocky
 * @date 2023-12-13
 */
@RestController
public class DifferentReteOpenController extends BaseController
{
    @Autowired
    private IDifferentReteService differentReteService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private WeixinFsfunction weixinFsfunction;

    @Autowired
    private WeixinGetOpenId weixinGetOpenId;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    /**
     * 查询异网数据列表
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:list')")
    @GetMapping("/list")
    public TableDataInfo list(DifferentRete differentRete)
    {
        startPage();
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        return getDataTable(list);
    }

    /**
     * 导出异网数据列表
     */
   // @PreAuthorize("@ss.hasPermi('different:rete:export')")
    @Log(title = "异网数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DifferentRete differentRete)
    {
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        ExcelUtil<DifferentRete> util = new ExcelUtil<DifferentRete>(DifferentRete.class);
        util.exportExcel(response, list, "异网数据数据");
    }

    /**
     * 获取异网数据详细信息
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(differentReteService.selectDifferentReteById(id));
    }

    /**
     * 新增异网数据
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:add')")
  /*  @Log(title = "异网数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DifferentRete differentRete)
    {
        return toAjax(differentReteService.insertDifferentRete(differentRete));
    }
*/
    /**
     * 修改异网数据
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:edit')")
    @Log(title = "异网数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DifferentRete differentRete)
    {
        return toAjax(differentReteService.updateDifferentRete(differentRete));
    }

    /**
     * 删除异网数据
     */
    //@PreAuthorize("@ss.hasPermi('different:rete:remove')")
    @Log(title = "异网数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(differentReteService.deleteDifferentReteByIds(ids));
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    //手机号查重
   // @PreAuthorize("@ss.hasPermi('different:rete:query')")
    @PostMapping(value = "/selectByPhone")
    public AjaxResult selectByPhone(@RequestBody DifferentRete differentRete)
    {
        return success(differentReteService.selectByPhone(differentRete));
    }


    //转化次数接口

    @GetMapping("/listCount")
    public Map<Integer, Long> listCount(DifferentRete differentRete)
    {
        List<DifferentRete> list = differentReteService.selectDifferentReteList(differentRete);
        Map<Integer, Long> collect = list.stream().collect(Collectors.groupingBy(DifferentRete::getFollowupTimes, Collectors.counting()));
        LinkedHashMap<Integer, Long> objectObjectLinkedHashMap = new LinkedHashMap<>();
        collect.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x->objectObjectLinkedHashMap.put(x.getKey(),x.getValue()));
        return objectObjectLinkedHashMap;
    }



    @PostMapping("/addUser")
    public AjaxResult add(@Validated @RequestBody WxAddBody wxAddBody) {
        String code = wxAddBody.getCode();
        String encryptedIv = wxAddBody.getEncryptedIv();
        SysUser user = wxAddBody.getSysUser();
        String encryptedData = wxAddBody.getEncryptedData();
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        //user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        Map<String, String> xcxOpenId = weixinGetOpenId.getXcxOpenId(code, encryptedIv, encryptedData);
        user.setOpenId(xcxOpenId.get("openId"));
        user.setUnionId(xcxOpenId.get("unionid"));
        int i = userService.insertUser(user);


        //获取公众号gzopenid
    /*
    1、已经有了用户信息，客户拿到用户所有信息
    2、获取公众号列表
    3、获取数据库列表

    * */
        weixinGetOpenId.getGzhOpenid();


//这是发消息

        /*
         * 1、拿到该支局的所有人userid
         * 在角色表中找到对应的人，并判断支局长角色 返回userid
         * 2、找到该支局的支局长 角色101
         *
         * */
       /* Long deptId = user.getDeptId();
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);*/
        long zjzid = 0;
        //sysUser.setRoleId(101l);

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getDeptId, user.getDeptId())
                .ne(SysUser::getDelFlag, 2);
        List<SysUser> sysUsers = userService.list(sysUserQueryWrapper);
        if (sysUsers.size() > 0) {
            // List<SysUser> sysUsers = userService.selectUserListOpen(sysUser);
            //SysUser sysUser1 = sysUsers.get(0);
            List<Long> collect = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
            for (Long aLong : collect) {
                List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleByUserId(aLong);
                if (Objects.nonNull(sysUserRoles) && sysUserRoles.size() > 0) {
                    Long roleId = sysUserRoles.get(0).getRoleId();
                    if (roleId.equals(101l)) {
                        zjzid = aLong;
                        break;
                    }
                }
        }


            /*List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleAll();
            long zjzid = 0;
            for (int i1 = 0; i1 < collect.size(); i1++) {
                for (int i2 = 0; i2 < sysUserRoles.size(); i2++) {
                    if (collect.get(i1).equals(sysUserRoles.get(i2).getUserId()) && sysUserRoles.get(i2).getRoleId().equals(101l)) {
                        zjzid = sysUserRoles.get(i2).getUserId();
                        break;
                    }
                }
            }*/

        }
           // SysUser sysUser1 = userService.selectUserById(zjzid);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserId, zjzid);
        SysUser sysUser1 = userService.getOne(queryWrapper);
        System.out.println("openid" + sysUser1.getGzhopenId());
            String openId = sysUser1.getGzhopenId();
            TreeMap<String, String> miniprograms = new TreeMap<String, String>();
            miniprograms.put("appid", "wx19b86a5fba0825ce");
            miniprograms.put("pagepath", "/pages/userExam/userExam");
            ArrayList<String> strings = new ArrayList<>();
            strings.add("thing1");
            strings.add("thing7");
            strings.add("phone_number5");
            strings.add("time4");

            ArrayList<String> strings1 = new ArrayList<>();
            strings1.add(user.getNickName());
            strings1.add(sysUser1.getNickName());
            strings1.add(user.getPhonenumber());
            strings1.add(DateUtil.formatDate(new Date()));
            weixinFsfunction.sendWarningByWechat(openId, miniprograms, strings, strings1, "An3-s0hltLVyysZOSSNTkflokVZ7VYhbjSmJ7V8JRQk");

            return toAjax(i);

    }



    @PostMapping("/addUserht")
    public AjaxResult addht(@Validated @RequestBody WxAddBody wxAddBody) {
       // String code = wxAddBody.getCode();
       // String encryptedIv = wxAddBody.getEncryptedIv();
        SysUser user = wxAddBody.getSysUser();
       // String encryptedData = wxAddBody.getEncryptedData();
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        //user.setCreateBy(getUsername());
        String Gzhopenid = weixinGetOpenId.getGzhOpenidByCode(wxAddBody.getCode());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
       // Map<String, String> xcxOpenId = weixinGetOpenId.getXcxOpenId(code, encryptedIv, encryptedData);
        user.setGzhopenId(Gzhopenid);
        //user.setUnionId(xcxOpenId.get("unionid"));
        int i = userService.insertUser(user);

        long zjzid = 0;
        //sysUser.setRoleId(101l);

        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.lambda().eq(SysUser::getDeptId, user.getDeptId())
                .ne(SysUser::getDelFlag, 2);
        List<SysUser> sysUsers = userService.list(sysUserQueryWrapper);
        if (sysUsers.size() > 0) {
            // List<SysUser> sysUsers = userService.selectUserListOpen(sysUser);
            //SysUser sysUser1 = sysUsers.get(0);
            List<Long> collect = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList());
            for (Long aLong : collect) {
                List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleByUserId(aLong);
                if (Objects.nonNull(sysUserRoles) && sysUserRoles.size() > 0) {
                    Long roleId = sysUserRoles.get(0).getRoleId();
                    if (roleId.equals(101l)) {
                        zjzid = aLong;
                        break;
                    }
                }
            }


            /*List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectUserRoleAll();
            long zjzid = 0;
            for (int i1 = 0; i1 < collect.size(); i1++) {
                for (int i2 = 0; i2 < sysUserRoles.size(); i2++) {
                    if (collect.get(i1).equals(sysUserRoles.get(i2).getUserId()) && sysUserRoles.get(i2).getRoleId().equals(101l)) {
                        zjzid = sysUserRoles.get(i2).getUserId();
                        break;
                    }
                }
            }*/

        }
        // SysUser sysUser1 = userService.selectUserById(zjzid);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserId, zjzid);
        SysUser sysUser1 = userService.getOne(queryWrapper);
        System.out.println("openid" + sysUser1.getGzhopenId());
        String openId = sysUser1.getGzhopenId();
        TreeMap<String, String> miniprograms = new TreeMap<String, String>();
        miniprograms.put("appid", "wx19b86a5fba0825ce");
        miniprograms.put("pagepath", "/pages/userExam/userExam");
        ArrayList<String> strings = new ArrayList<>();
        strings.add("thing1");
        strings.add("thing7");
        strings.add("phone_number5");
        strings.add("time4");

        ArrayList<String> strings1 = new ArrayList<>();
        strings1.add(user.getNickName());
        strings1.add(sysUser1.getNickName());
        strings1.add(user.getPhonenumber());
        strings1.add(DateUtil.formatDate(new Date()));
        weixinFsfunction.sendWarningByWechat(openId, miniprograms, strings, strings1, "An3-s0hltLVyysZOSSNTkflokVZ7VYhbjSmJ7V8JRQk");

        return toAjax(i);

    }


    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        //user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
       // user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @PostMapping("/removeUser")
    public AjaxResult removeUser(@RequestBody SysUser user)
    {
     /*   if (ArrayUtils.contains(, getUserId()))
        {
            return error("当前用户不能删除");
        }*/
        return toAjax(userService.deleteUserById(user.getUserId()));
    }


    @PostMapping("/listDept")
    public AjaxResult list(@RequestBody SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptListOpen(dept);
        return success(depts);
    }

    @PostMapping("/sendvx")
    public AjaxResult sendvx(@RequestBody Map<String,String> map)
    {
        String openid = map.get("openid");
        TreeMap<String, String> miniprograms = new TreeMap<String, String>();
            miniprograms.put("appid","wx19b86a5fba0825ce");
            miniprograms.put("pagepath","/pages/userExam/userExam");//
        ArrayList<String> strings = new ArrayList<>();
        strings.add("thing1");
        strings.add("thing7");
        strings.add("phone_number5");
        strings.add("time4");

        ArrayList<String> strings1 = new ArrayList<>();
        strings1.add("test1");
        strings1.add("test2");
        strings1.add("12345678910");
        strings1.add("2023-12-26");
        weixinFsfunction.sendWarningByWechat(openid,miniprograms,strings,strings1,"An3-s0hltLVyysZOSSNTkflokVZ7VYhbjSmJ7V8JRQk");


        return success();
    }


    @PostMapping("/UpdateData")
    public void UpdateData() {

        weixinGetOpenId.getGzhOpenid();

    }





}
